package processor
{
	import data.ToneGate;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	[Event(name="connect",type="flash.events.Event")]
	
	public class Output extends EventDispatcher
	{
		private var hostName:String = "localhost";
		private var port:uint = 5331;
		private var socket:Socket;
		
		public var isConnected:Boolean;
		
		public function Output(target:IEventDispatcher=null)
		{
			super(target);
			this.setupSocket();
		}
		
		private function setupSocket():void
		{
			socket = new Socket();
			socket.addEventListener( ProgressEvent.SOCKET_DATA, handleSocketData );
			socket.addEventListener( IOErrorEvent.IO_ERROR, handleSocketError );
			socket.addEventListener( Event.CONNECT, handleSocketConnect );
		}
		
		protected function handleSocketData( e:ProgressEvent ):void
		{
			if( socket.bytesAvailable > 0)
			{
				//trace( socket.readUTFBytes( socket.bytesAvailable ) );
			}
		}
		
		protected function handleSocketError( e:IOErrorEvent ):void
		{
			this.dispatchEvent( e.clone() );
			isConnected = false;
		}
		
		protected function handleSocketConnect( e:Event ):void
		{
			this.dispatchEvent( e.clone() );
			isConnected = true;
		}
		
		public function sendToOutput( outData:ToneGate ):void
		{
			if( isConnected )
			{
				socket.writeByte( outData.tone );
				socket.writeByte( outData.gate );
				socket.flush();
			}
		}
		
		public function connect( ):void
		{
			if( !isConnected )
				socket.connect( hostName, port );
			else
				socket.close();
		}
		
		
	
	}
}